package com.dwin.dingnuo.ui.base;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;


import com.dwin.dingnuo.R;
import com.dwin.dingnuo.http.beans.UserBean;
import com.dwin.dingnuo.ui.system.LoginActivity;
import com.dwin.dingnuo.utils.Constants;
import com.dwin.dingnuo.utils.LocalManageUtil;
import com.dwin.dingnuo.utils.ToastUtil;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

/**
 * Activity 基类
 */
public class BaseActivity extends AppCompatActivity {
    protected SharedPreferences logMessage = null; //用户日志保存
    protected Context mContext;
    protected Resources mRes;

    protected UserBean mUser;
    protected String language = "zh"; //en, zh
    protected boolean isCanHandleClick = true; // 是否可以点击UI元素
    protected static final int PAGE_SIZE = 30; // 每页条数。
    protected static final int CODE_100 = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity", getClass().getSimpleName());
        mRes = getResources();
        mContext = this;
        logMessage = getSharedPreferences("logmessage", MODE_PRIVATE);
        language = logMessage.getString("language", "zh");

        List<UserBean> list = LitePal.findAll(UserBean.class);
        if (list != null && list.size() > 0) {
            mUser = list.get(0); // 获取用户信息
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            //非默认值
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) { //非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults(); //设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.setLocal(newBase));
    }

    public void userLogout() {
        ToastUtil.toastShort(this, getResources().getString(R.string.token_expired_login_again));
        LitePal.deleteAll(UserBean.class); // 先删除所有用户数据
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK | intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public FragmentTransaction getSupportFragmentTransaction() {
        return getSupportFragmentManager().beginTransaction();
    }

    public boolean onActivityBackPressed() {
        super.onBackPressed();
        return true;
    }

    protected <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    @Nullable
    @SuppressWarnings("unchecked")
    protected <T extends BaseFragment> T findFragment(int id) {
        return (T) getSupportFragmentManager().findFragmentById(id);
    }

    @Nullable
    @SuppressWarnings("unchecked")
    protected <T extends BaseFragment> T findFragment(String tag) {
        return (T) getSupportFragmentManager().findFragmentByTag(tag);
    }

    protected void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    protected void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    protected void toggleSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.toggleSoftInput(0, 0);
        }
    }

    protected String getVersionName() {
        String version = null;
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    // 判断WiFi是否连接
    protected boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

    // 获取当前手机连接wifi网络的mac地址
    protected String getWifiMac() {
        WifiManager wifimanager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiinfo = wifimanager.getConnectionInfo();
        return wifiinfo.getBSSID();
    }

    /**
     * 权限检查方法
     *
     * @param permissions 权限数组
     * @return
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 提供权限请求方法
     *
     * @param code
     * @param permissions
     */
    public void requestPermissions(int code, String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, code);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constants.WRITE_EXTERNAL_CODE:
                doSDCardPermission();
                break;
            case Constants.PHONE_CODE:
                doCallPhone();
                break;
            case Constants.WIFI_PERMISSION_CODE:
                doScanWifis();
                break;
            case Constants.COARSE_LOCATION_CODE:
                List<String> deniedList = new ArrayList<>(); // 遍历所有申请的权限，把被拒绝的权限放入集合
                for (int i = 0; i < grantResults.length; i++) {
                    int grantResult = grantResults[i];
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
//                       用户同意权限
                    } else {
                        deniedList.add(permissions[i]);
                    }
                }
                if (deniedList.isEmpty()) {
                    doCoarseLocation();
                } else {
                    ToastUtil.toastShort(mContext, getResources().getString(R.string.location_permission_required));
                }
                break;
            case Constants.CAMERA_CODE:
                doCameraPermission();
                break;
            case Constants.RECORD_AUDIO:
                doRecordAudioPermission();
                break;
        }
    }

    public void doRecordAudioPermission() {
    }

    // 父类提供默认的权限处理方法
    public void doSDCardPermission() {
    }

    // 获得拍照，存储空间的访问权限
    public void doCameraPermission() {
    }

    public void doCallPhone() {
    }

    public void doScanWifis() {
    }

    public void doCoarseLocation() {
    }

    protected void initViews() {
    }

    PopupWindow popupWindow;

    protected void dismissMqttDialog() {
        isCanHandleClick = true;
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    protected void showMqttDialog() {
        isCanHandleClick = false;
        if (popupWindow.isShowing()) {
            return;
        } else { // 未显示
            popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    dismissMqttDialog();
                }
            }, 950);
        }
    }

    public static String replaceLast(String string, String match, String replace) {
        if (null == replace) {
            //参数不合法，原样返回
            return string;
        }
        StringBuilder sBuilder = new StringBuilder(string);
        int lastIndexOf = sBuilder.lastIndexOf(match);
        if (-1 == lastIndexOf) {
            return string;
        }
        return sBuilder.replace(lastIndexOf, lastIndexOf + match.length(), replace).toString();
    }

}
